package com.jdjw.modules.wfactivity.service.impl;

import com.jdjw.modules.busassetapply.entity.BusAssetApply;
import com.jdjw.modules.sysuser.entity.SysUser;
import com.jdjw.modules.sysuser.mapper.SysUserMapper;
import com.jdjw.modules.wfactivity.entity.WfActivity;
import com.jdjw.modules.wfactivity.mapper.WfActivityMapper;
import com.jdjw.modules.wfactivity.service.WfActivityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jdjw.modules.wfnode.entity.WfNode;
import com.jdjw.modules.wfnode.mapper.WfNodeMapper;
import com.jdjw.modules.wftask.entity.WfTask;
import com.jdjw.modules.wftask.mapper.WfTaskMapper;
import com.jdjw.modules.wftempactivity.entity.WfTempActivity;
import com.jdjw.modules.wftempactivity.mapper.WfTempActivityMapper;
import com.jdjw.modules.wftempnode.entity.WfTempNode;
import com.jdjw.modules.wftempnode.mapper.WfTempNodeMapper;
import com.jdjw.modules.wftempnoderole.entity.WfTempNodeRole;
import com.jdjw.modules.wftempnoderole.mapper.WfTempNodeRoleMapper;
import com.jdjw.utils.SpringUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * wf_activity 服务实现类
 * </p>
 *
 * @author fq
 * @since 2021-07-13
 */
@Service
@Transactional
public class WfActivityServiceImpl extends ServiceImpl<WfActivityMapper, WfActivity> implements WfActivityService {

    //流程实例状态:1运行中2结束3终止4暂停
    private final String STATUS_RUN = "01";
    private final String STATUS_FINISH = "02";
    private final String STATUS_END = "03";
    private final String STATUS_PAUSE = "04";
    //处理类型;01岗位内流转02下一节点03退回
    private final String DUAL_TYPE_INSIDE = "01";
    private final String DUAL_TYPE_NEXT = "02";
    private final String DUAL_TYPE_BACK = "03";

    @Autowired
    private WfActivityMapper wfActivityMapper;

    @Autowired
    private WfNodeMapper wfNodeMapper;

    @Autowired
    private WfTempNodeMapper wfTempNodeMapper;

    @Autowired
    private WfTempActivityMapper wfTempActivityMapper;

    @Autowired
    private WfTaskMapper wfTaskMapper;

    @Autowired
    private WfTempNodeRoleMapper wfTempNodeRoleMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public String findNodeCode(String applyId) {

        //1、查询当前流程实例，当前节点
        WfActivity activity = new WfActivity();
        activity.setApplyId(applyId);

        activity =wfActivityMapper.queryByApplyId(applyId);

        Map<String,Object> map=new HashMap<>();
//        map.put("status",STATUS_RUN);
        map.put("activity_id", activity.getId());
        List<WfNode> wfNodes = wfNodeMapper.selectByMap(map);

        WfNode currentNode = wfNodes.get(0); // 当前有效节点
        WfTempNode wfTempNode = wfTempNodeMapper.selectById(currentNode.getTempNodeId());

        return wfTempNode.getNodeLogo();

    }

    @Override
    public String createWorkFlow(String logo,String deptId,String id,String createBy,String userName ) throws Exception {
        try {
            // WfActivity activityCheck = new WfActivity();
            // activityCheck.setApplyId(applyId);
            // activityCheck = activityDao.selectOne(activityCheck);
            // if (activityCheck != null) {
            //     return "FINISH";
            // }

            String officeId = deptId;

            // officeId = UserUtils.getUser().getOffice().getId();
            //根据受理机构和流程标识符查询出对应的流程定义模板
            //查询流程模板定义表
            List<WfTempActivity> tempActivityList = wfTempActivityMapper.queryByLogo(logo);
            if (tempActivityList == null && tempActivityList.size() == 0) {
                //流程定义对象不存在流程创建失败，返回FAIL
                throw new Exception();
            }
            WfTempActivity tempActivity = tempActivityList.get(0);
            //1、保存流程实例表
            WfActivity activity = new WfActivity();
            // activity.preInsert();//生成activity主键
            activity.setId(getUuid());
            activity.setCreateBy(createBy);
            SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            activity.setCreateDate(s.format(new Date()));
            activity.setUpdateBy(createBy);
            activity.setUpdateDate(s.format(new Date()));
            activity.setDelFlag("0");

            // activity.setTempActivity(tempActivity);
            activity.setTempActivityId(tempActivity.getId());
            activity.setTempActivityName(tempActivity.getName());
            activity.setOfficeId(officeId);
            activity.setApplyId(id);//申请ID
            activity.setStatus("01");//流程实例状态:1运行中2结束3终止4暂停
            wfActivityMapper.insert(activity);

            //2、保存节点表
            List<WfTempNode> tempNodeList = wfTempNodeMapper.queryByTempActivityId(tempActivity.getId());//wfTempNodeMapper

            if (null == tempNodeList || tempNodeList.size() == 0) {
                //流程定义节点对象不存在流程创建失败，返回FAIL
                throw new Exception();
            }
            //查询结果是按照节点优先级排序的，所以创建流程取第一个值就是第一个节点
            WfTempNode tempNode = tempNodeList.get(0);
            WfNode node = new WfNode();
            // node.preInsert();
            node.setId(getUuid());
            node.setCreateBy(createBy);
            node.setCreateDate(new Date());
            node.setUpdateBy(createBy);
            node.setUpdateDate(new Date());

            // node.setTempNode(tempNode);
            // node.setActivity(activity);
            node.setId(getUuid());
            node.setTempNodeId(tempNode.getId());
            node.setName(tempNode.getName());
            node.setActivityId(activity.getId());
            node.setStatus("01");//流程实例状态:1运行中2结束3终止4暂停
            wfNodeMapper.insert(node);
            //3、保存任务表
            WfTask task = new WfTask();
            // task.preInsert();
            task.setId(getUuid());
            task.setCreateBy(createBy);
            task.setCreateDate(new Date());
            task.setUpdateBy(createBy);
            task.setUpdateDate(new Date());

            task.setId(getUuid());
            task.setActivityId(activity.getId());
            task.setNodeId(node.getId());
            task.setNodeName(tempNode.getName());
            task.setUpdateName(userName);
            task.setCreateName(userName);
            task.setStatus("01");//流程实例状态:1运行中2结束3终止4暂停
            task.setDualType("02");//处理类型;01岗位内流转02下一节点03退回
            wfTaskMapper.insert(task);
            return "SUCCESS";
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception();
        }

    }


    /**
     * 发送到下一节点所有人
     *
     * @param officeId(为空时候就发送到该角色所有人，不为空时候发送到该组织机构下面的拥有该角色的人员)
     * @param
     */
    @Transactional(readOnly = false)
    public String sendNextNodeAllPerson(String id,String userId,String userName, String officeId, WfTask currentTaskParam) throws Exception {
        try {

            //1、查询当前流程实例，当前节点
            WfActivity activity = new WfActivity();
            activity.setApplyId(id);
            activity =wfActivityMapper.queryByApplyId(id);
            Map<String,Object> map=new HashMap<>();
            map.put("status",01);
            map.put("activity_id", activity.getId());
            List<WfNode> currentNodeList = wfNodeMapper.selectByMap(map);
            WfNode currentNode = currentNodeList.get(0); // 当前有效节点

            //2、流程节点模板中查询下一节点(nextTempNote)
            WfTempNode nextTempNode = getNextTempNode(activity.getTempActivityId(), currentNode.getTempNodeId());
            //下一节点不存在，发送失败
            if (null == nextTempNode || StringUtils.isBlank(nextTempNode.getId())) {
                throw new Exception();
            }
            //3、当前结点为运行中的改为已完成
            // currentNode.preUpdate();
            currentNode.setUpdateBy(userId);
            currentNode.setUpdateDate(new Date());

            currentNode.setStatus(STATUS_FINISH);
            // nodeDao.update(currentNode);
            wfNodeMapper.updateById(currentNode);
            //4、把当前用户任务记录状态为运行中的记录改为已完成
            Map<String,Object> maps=new HashMap<>();
            maps.put("node_id", currentNode.getId());
//            maps.put("update_by", busAssetApply.getUserId());
            maps.put("status", STATUS_RUN);
            List<WfTask> currentTaskList = wfTaskMapper.selectByMap(maps);
            WfTask currentTask = currentTaskList.get(0);
            // currentTask.preUpdate();//更新任务节点修改信息
            currentTask.setUpdateBy(userId);
            currentTask.setUpdateDate(new Date());

            currentTask.setStatus(STATUS_FINISH);// 已完成
            currentTask.setOpinionContent(currentTaskParam.getOpinionContent());
            currentTask.setDualOpinion(currentTaskParam.getDualOpinion());
            currentTask.setAttIds(currentTaskParam.getAttIds());
            // currentTask.preUpdate();
            currentTask.setUpdateBy(userId);
            currentTask.setUpdateDate(new Date());

            currentTask.setUpdateName(userName);
            wfTaskMapper.updateById(currentTask);

            //5、删除当前状态为运行中的任务记录
            Map<String,Object> mapstwo =new HashMap<>();
            mapstwo.put("node_id", currentTask.getNodeId());
            mapstwo.put("status", STATUS_RUN);
            wfTaskMapper.deleteByMap(mapstwo);

            //6、添加流程实例下一个节点
            WfNode nodeNext = new WfNode();
            // nodeNext.preInsert();
            nodeNext.setId(getUuid());
            nodeNext.setCreateBy(userId);
            nodeNext.setCreateDate(new Date());
            nodeNext.setUpdateBy(userId);
            nodeNext.setUpdateDate(new Date());

            // nodeNext.setTempNode(nextTempNode);
            // nodeNext.setActivity(activity);
            nodeNext.setTempNodeId(nextTempNode.getId());
            nodeNext.setName(nextTempNode.getName());
            nodeNext.setActivityId(activity.getId());
            nodeNext.setStatus(STATUS_RUN);
            wfNodeMapper.insert(nodeNext);
            //7、创建任务记录（创建的记录数是和人员数是一一对应的）

            Map<String,Object> mapthree=new HashMap<>();
            mapthree.put("temp_node_id", nextTempNode.getId());
            List<WfTempNodeRole> tempNodeRoleList = wfTempNodeRoleMapper.selectByMap(mapthree);

            StringBuffer roleIds = new StringBuffer();
            int i = 0;
            for (WfTempNodeRole tempNodeRoleOne : tempNodeRoleList) {
                roleIds.append("'").append(tempNodeRoleOne.getRoleId()).append("',");
            }
            //String str = roleIds.toString().substring(1,roleIds.length()-2);
            if (roleIds != null && roleIds.length() > 0) {


                Map<String, String> mapfour = new HashMap<String, String>();
                mapfour.put("roleId", roleIds.toString().substring(1, roleIds.length() - 2));
                mapfour.put("officeId", officeId);
                List<SysUser> userList = sysUserMapper.selectUserListByRoleOffice(mapfour);//查找下一节点的人


                //如果没有人就算归档,remark 显示的是roleId，这边如果一个人在两个角色里面，就出现两条记录（这边是为了需求原因，本系统采用了角色区分）
                WfTask taskNext = new WfTask();
                taskNext.setActivityId(activity.getId());
                taskNext.setNodeId(nodeNext.getId());
                taskNext.setNodeName(nextTempNode.getName());
                taskNext.setCreateName(userName);
                taskNext.setStatus(STATUS_RUN);
                for (SysUser userTemp : userList) {
                    // taskNext.preInsert();
                    taskNext.setId(getUuid());
                    taskNext.setCreateBy(userId);
                    taskNext.setCreateDate(new Date());
                    taskNext.setUpdateDate(new Date());

                    taskNext.setUpdateBy(userTemp.getId());
                    taskNext.setUpdateName(userTemp.getUsername());
                    taskNext.setDualType(DUAL_TYPE_NEXT);//01 岗位内流转 02 下一节点 03 退回
                    taskNext.setLastTaskId(currentTask.getId());
                    wfTaskMapper.insert(taskNext);
                }
            }
            return "SUCCESS";
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception();
        }
    }

    /**
     * 发送到下一节点指定人
     *
     * @param
     */
    @Transactional(readOnly = false)
    public String sendNextNoteDesingnatedPerson(String id,String userId,String userName, String[] userIds, WfTask currentTaskParam) {
        //1、查询当前流程实例，当前节点
        WfActivity activity = new WfActivity();
        activity.setApplyId(id);
        activity =wfActivityMapper.queryByApplyId(id);
        Map<String,Object> map=new HashMap<>();
        map.put("status",01);
        map.put("activity_id", activity.getId());
        List<WfNode> currentNodeList = wfNodeMapper.selectByMap(map);
        WfNode currentNode = currentNodeList.get(0); // 当前有效节点

        //2、流程节点模板中查询下一节点(nextTempNote)
        WfTempNode nextTempNode = getNextTempNode(activity.getTempActivityId(), currentNode.getTempNodeId());
        //3、当前结点为运行中的改为已完成
        // currentNode.preUpdate(); // 更新tBaNote信息
        currentNode.setUpdateBy(userId);
        currentNode.setUpdateDate(new Date());

        currentNode.setStatus(STATUS_FINISH);
        wfNodeMapper.updateById(currentNode);
        //4、把当前用户任务记录状态为运行中的记录改为已完成

        Map<String,Object> mapone=new HashMap<>();
        mapone.put("node_id", currentNode.getId());
        mapone.put("update_by", userId);
        mapone.put("status", STATUS_RUN);
        List<WfTask> currentTaskList = wfTaskMapper.selectByMap(mapone);
        WfTask currentTask = currentTaskList.get(0); // 当前有效节点
        currentTask.setStatus(STATUS_FINISH);// 已完成
        // currentTask.preUpdate();
        currentTask.setUpdateBy(userId);
        currentTask.setUpdateDate(new Date());

        currentTask.setUpdateName(userName);
        currentTask.setOpinionContent(currentTaskParam.getOpinionContent());
        currentTask.setDualOpinion(currentTaskParam.getDualOpinion());
        currentTask.setAttIds(currentTaskParam.getAttIds());
        wfTaskMapper.updateById(currentTask);

        //5、删除当前状态为运行中的任务记录
        Map<String,Object> maptow=new HashMap<>();
        maptow.put("node_id", currentTask.getNodeId());
        maptow.put("status", STATUS_RUN);
        wfTaskMapper.deleteByMap(maptow);

        //6、具体流程中添加下一个节点
        WfNode nodeNext = new WfNode();
        // nodeNext.preInsert();
        nodeNext.setId(getUuid());
        nodeNext.setCreateBy(userId);
        nodeNext.setCreateDate(new Date());
        nodeNext.setUpdateBy(userId);
        nodeNext.setUpdateDate(new Date());

        nodeNext.setName(nextTempNode.getName());
        nodeNext.setTempNodeId(nextTempNode.getId());
        nodeNext.setActivityId(activity.getId());
        nodeNext.setStatus(STATUS_RUN);
        wfNodeMapper.insert(nodeNext);
        //7、创建任务记录（这里根据直接发送给userId）
        for (int i = 0; i < userIds.length; i++) {
            SysUser userNext = sysUserMapper.selectById(userIds[i]);
            WfTask taskNext = new WfTask();
            // taskNext.preInsert();
            taskNext.setId(getUuid());
            taskNext.setCreateBy(userId);
            taskNext.setCreateDate(new Date());
            taskNext.setUpdateBy(userId);
            taskNext.setUpdateDate(new Date());

            taskNext.setActivityId(activity.getId());
            taskNext.setNodeId(nodeNext.getId());
            taskNext.setNodeName(nextTempNode.getName());
            taskNext.setCreateName(userName);
            taskNext.setStatus(STATUS_RUN);
            taskNext.setUpdateBy(userNext.getId());
            taskNext.setUpdateName(userNext.getUsername());
            taskNext.setDualType(DUAL_TYPE_NEXT);
            taskNext.setLastTaskId(currentTask.getId());
            wfTaskMapper.insert(taskNext);
        }
        return "SUCCESS";
    }

    /**
     * 流程退回（当前处理人，把信息退回到上一处理人，其实就是做了一次插入操作）
     */
    @Transactional(readOnly = false)
    public String sendBack(String id,String userId,String userName, String officeId, WfTask currentTaskParam) throws Exception {
        //找到上一节点处理人，复制处理人task，节点也复制
        try {
            //1、查询当前流程实例，当前节点
            WfActivity activity = new WfActivity();
            activity.setApplyId(id);
            activity =wfActivityMapper.queryByApplyId(id);
            Map<String,Object> map=new HashMap<>();
            map.put("status",01);
            map.put("activity_id", activity.getId());
            List<WfNode> currentNodeList = wfNodeMapper.selectByMap(map);
            WfNode currentNode = currentNodeList.get(0); // 当前有效节点

            //2、流程节点模板中查询下一节点(nextTempNote)
            WfTempNode nextTempNode = getNextTempNode(activity.getTempActivityId(), currentNode.getTempNodeId());
            //下一节点不存在，发送失败
            if (null == nextTempNode || StringUtils.isBlank(nextTempNode.getId())) {
                throw new Exception();
            }
            //3、当前结点为运行中的改为已完成
            // currentNode.preUpdate();
            currentNode.setUpdateBy(userId);
            currentNode.setUpdateDate(new Date());

            currentNode.setStatus(STATUS_FINISH);
            wfNodeMapper.updateById(currentNode);
            //4、把当前用户任务记录状态为运行中的记录改为已完成

            Map<String,Object> mapone=new HashMap<>();
            mapone.put("node_id", currentNode.getId());
            mapone.put("update_by", userId);
            mapone.put("status", STATUS_RUN);
            List<WfTask> currentTaskList = wfTaskMapper.selectByMap(mapone);
            WfTask currentTask = currentTaskList.get(0); // 当前有效节点

            // currentTask.preUpdate();//更新任务节点修改信息
            currentTask.setUpdateBy(userId);
            currentTask.setUpdateDate(new Date());

            currentTask.setStatus(STATUS_FINISH);// 已完成
            currentTask.setOpinionContent(currentTaskParam.getOpinionContent());
            currentTask.setDualOpinion(currentTaskParam.getDualOpinion());
            currentTask.setAttIds(currentTaskParam.getAttIds());
            // currentTask.preUpdate();
            currentTask.setUpdateBy(userId);
            currentTask.setUpdateDate(new Date());

            currentTask.setUpdateName(userName);
            wfTaskMapper.updateById(currentTask);
            //5、删除当前状态为运行中的任务记录
            Map<String,Object> maptwo= new HashMap<>();
            maptwo.put("node_id", currentTask.getNodeId());
            maptwo.put("status", STATUS_RUN);
            wfTaskMapper.deleteByMap(maptwo);

            //6、添加流程实例下一个节点
            WfTask taskNext = wfTaskMapper.selectById(currentTask.getLastTaskId());//上一节点任务对象
            WfNode nodeNext = wfNodeMapper.selectById(taskNext.getNodeId());//退回获取上次发送人的，节点数据
            nodeNext.setId("");
            // nodeNext.preInsert();
            nodeNext.setId(getUuid());
            nodeNext.setCreateBy(userId);
            nodeNext.setCreateDate(new Date());
            nodeNext.setUpdateBy(currentTask.getCreateBy());
            nodeNext.setUpdateDate(new Date());

            nodeNext.setStatus(STATUS_RUN);
            wfNodeMapper.insert(nodeNext);
            //7、创建任务记录
            taskNext.setId("");
            taskNext.setCreateName(userName);
            taskNext.setStatus(STATUS_RUN);
            // taskNext.preInsert();
            taskNext.setId(getUuid());
            taskNext.setCreateBy(userId);
            taskNext.setCreateDate(new Date());
            taskNext.setUpdateBy(currentTask.getCreateBy());
            taskNext.setUpdateDate(new Date());
            taskNext.setNodeId(nodeNext.getId());
            taskNext.setDualType(DUAL_TYPE_BACK);//01 岗位内流转 02 下一节点 03 退回
            taskNext.setLastTaskId(currentTask.getId());
            wfTaskMapper.insert(taskNext);
            return "SUCCESS";
        } catch (Exception e) {
            // logger.error(e.getMessage());
            throw new Exception();
        }
    }

    @Override
    public int findActivitySubmit(String applyId) {
        int checkFlag = 0; // 0 未提交 1 已提交

        Map<String,Object> map=new HashMap<>();
        map.put("apply_id",applyId);
        List<WfActivity> wfActivities = wfActivityMapper.selectByMap(map);

        Map<String,Object> map2=new HashMap<>();
        map2.put("activity_id", wfActivities.get(0).getId());
        map2.put("status", STATUS_FINISH);
        List<WfTask> currentTaskList = wfTaskMapper.selectByMap(map2);
        if (currentTaskList != null && currentTaskList.size() > 0) {
            checkFlag = 1;
        }
        return checkFlag;
    }

    /**
     * 发送到指定节点所有人
     *
     * @param officeId(为空时候就发送到该角色所有人，不为空时候发送到该组织机构下面的拥有该角色的人员)
     * @param
     */
    @Transactional(readOnly = false)
    public String sendAppointNodeAllPerson(String id,String userId,String userName, String officeId, String NextNodeCode, WfTask currentTaskParam) throws Exception {
        try {

            //1、查询当前流程实例，当前节点
            WfActivity activity = new WfActivity();
            activity.setApplyId(id);
            activity =wfActivityMapper.queryByApplyId(id);
            Map<String,Object> map=new HashMap<>();
            map.put("status",01);
            map.put("activity_id", activity.getId());
            List<WfNode> currentNodeList = wfNodeMapper.selectByMap(map);
            WfNode currentNode = currentNodeList.get(0);


            //2、流程节点模板中查询下一节点(nextTempNote)

            Map<String,Object> mapone=new HashMap<>();
            mapone.put("status", "1");
            mapone.put("node_logo", NextNodeCode);
            mapone.put("temp_activity_id", activity.getTempActivityId());
            List<WfTempNode> currentTempNodeList = wfTempNodeMapper.selectByMap(mapone);
            //下一节点不存在，发送失败
            if (null == currentTempNodeList || currentTempNodeList.size() == 0) {
                throw new Exception();
            }
            WfTempNode nextTempNode = currentTempNodeList.get(0);
            //下一节点不存在，发送失败
            if (null == nextTempNode || StringUtils.isBlank(nextTempNode.getId())) {
                throw new Exception();
            }
            //3、当前结点为运行中的改为已完成
            // currentNode.preUpdate();
            currentNode.setUpdateBy(userId);
            currentNode.setUpdateDate(new Date());

            currentNode.setStatus(STATUS_FINISH);
            // nodeDao.update(currentNode);
            wfNodeMapper.updateById(currentNode);
            //4、把当前用户任务记录状态为运行中的记录改为已完成

            Map<String,Object> maptow=new HashMap<>();
            maptow.put("node_id", currentNode.getId());
            maptow.put("update_by", userId);
            maptow.put("status", STATUS_RUN);
            List<WfTask> currentTaskList = wfTaskMapper.selectByMap(maptow);
            WfTask currentTask = currentTaskList.get(0);
            // currentTask.preUpdate();//更新任务节点修改信息
            currentTask.setUpdateBy(userId);
            currentTask.setUpdateDate(new Date());

            currentTask.setStatus(STATUS_FINISH);// 已完成
            currentTask.setOpinionContent(currentTaskParam.getOpinionContent());
            currentTask.setDualOpinion(currentTaskParam.getDualOpinion());
            currentTask.setAttIds(currentTaskParam.getAttIds());
            // currentTask.preUpdate();
            currentTask.setUpdateBy(userId);
            currentTask.setUpdateDate(new Date());

            currentTask.setUpdateName(userName);
            wfTaskMapper.updateById(currentTask);

            //5、删除当前状态为运行中的任务记录
            Map<String,Object> mapthree=new HashMap<>();
            mapthree.put("node_id", currentTask.getNodeId());
            mapthree.put("status", STATUS_RUN);
            wfTaskMapper.deleteByMap(mapthree);

            //6、添加流程实例下一个节点
            WfNode nodeNext = new WfNode();
            // nodeNext.preInsert();
            nodeNext.setId(getUuid());
            nodeNext.setCreateBy(userId);
            nodeNext.setCreateDate(new Date());
            nodeNext.setUpdateBy(userId);
            nodeNext.setUpdateDate(new Date());

            // nodeNext.setTempNode(nextTempNode);
            // nodeNext.setActivity(activity);
            nodeNext.setTempNodeId(nextTempNode.getId());
            nodeNext.setName(nextTempNode.getName());
            nodeNext.setActivityId(activity.getId());
            nodeNext.setStatus(STATUS_RUN);
            wfNodeMapper.insert(nodeNext);
            //7、创建任务记录（创建的记录数是和人员数是一一对应的）
            Map<String,Object> mapfour=new HashMap<>();
            mapfour.put("temp_node_id", nextTempNode.getId());
            List<WfTempNodeRole> tempNodeRoleList = wfTempNodeRoleMapper.selectByMap(mapfour);

            StringBuffer roleIds = new StringBuffer();
            int i = 0;
            for (WfTempNodeRole tempNodeRoleOne : tempNodeRoleList) {
                roleIds.append("'").append(tempNodeRoleOne.getRoleId()).append("',");
            }
            //String str = roleIds.toString().substring(1,roleIds.length()-2);
            if (roleIds != null && roleIds.length() > 0) {


                Map<String, String> maps = new HashMap<String, String>();
                maps.put("roleId", roleIds.toString().substring(1, roleIds.length() - 2));
                maps.put("officeId", officeId);
                List<SysUser> userList = sysUserMapper.selectUserListByRoleOffice(maps);//查找下一节点的人


                //如果没有人就算归档,remark 显示的是roleId，这边如果一个人在两个角色里面，就出现两条记录（这边是为了需求原因，本系统采用了角色区分）
                WfTask taskNext = new WfTask();
                taskNext.setActivityId(activity.getId());
                taskNext.setNodeId(nodeNext.getId());
                taskNext.setNodeName(nextTempNode.getName());
                taskNext.setCreateName(userName);
                taskNext.setStatus(STATUS_RUN);
                for (SysUser userTemp : userList) {
                    // taskNext.preInsert();
                    taskNext.setId(getUuid());
                    taskNext.setCreateBy(userId);
                    taskNext.setCreateDate(new Date());
                    taskNext.setUpdateDate(new Date());

                    taskNext.setUpdateBy(userTemp.getId());
                    taskNext.setUpdateName(userTemp.getUsername());
                    taskNext.setDualType(DUAL_TYPE_NEXT);//01 岗位内流转 02 下一节点 03 退回
                    taskNext.setLastTaskId(currentTask.getId());
                    wfTaskMapper.insert(taskNext);
                }
            }
            return "SUCCESS";
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception();
        }
    }



    public WfTempNode getNextTempNode(String tempActivityId, String currentNodeId) {
        //1、根据tempActivityId得到流程定义
        /**查找流程实例中，流程定义ID,获取节点集合，查找当前节点的ID,根据当前节点ID寻找下下一节点ID**/
        WfTempActivity tempActivity = wfTempActivityMapper.selectById(tempActivityId);
        List<WfTempNode> tempNodeList = wfTempNodeMapper.queryByTempActivityId(tempActivity.getId());
        tempActivity.setTempNodeList(tempNodeList);

        //2、获得当前流程定义节点
        WfTempNode currentTempNode = wfTempNodeMapper.selectById(currentNodeId);
        int i = 0;
        WfTempNode nextTempNode = new WfTempNode();
        //循环遍历找到当前节点的下一个节点
        for (WfTempNode tempNode : tempActivity.getTempNodeList()) {
            //因为tempActivity对象中的TempNodeList是按照优先级顺序排序的，所以当前节点下一有效的节点，按照顺序遍历即可
            if (i == 1 && tempNode.getStatus().equals("1") && tempNode.getPriority() > currentTempNode.getPriority()) {
                nextTempNode = tempNode;
                break;
            }
            //找到当前节点后，给i设置1,作为下一个节点返回的条件之一
            if (tempNode.getId().equals(currentTempNode.getId())) {
                i = 1;
            }
        }
        return nextTempNode;
    }


    //UUId生成
    private String getUuid() {

        return UUID.randomUUID().toString().replaceAll("-", "");
    }
}
